package seleniumUnit;

import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.imageio.ImageIO;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.util.FileUtils;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WrapsDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.events.EventFiringWebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.google.common.io.Files;

import javaUnit.ThreadTime;

public class linkOperate {
	private static final Logger log = LogManager.getLogger(linkOperate.class.getName());
	ExtentTest test;
	WebDriver driver;

	public linkOperate(ExtentTest test, WebDriver driver) {
		this.test = test;
		this.driver = driver;
	}

	/**
	 * 
	 * @param driver
	 * @param ele
	 * @param webTitle 超链接的IE标题
	 * @return
	 */
	public boolean moveEleClickLink(WebElement ele, String webTitle) {
		String whandle = driver.getWindowHandle();
		String herf = ele.getAttribute("href");
		boolean bl = false;
		ele.click();
		test.log(Status.INFO, "click WebElementlink=" + herf);
		Set<String> handles = driver.getWindowHandles();
		for (String handle : handles) {
			if (!handle.equals(whandle)) {
				driver.switchTo().window(handle);
				test.log(Status.INFO, "switchTO windows title=" + webTitle);
				try {
					WebDriverWait wait = new WebDriverWait(driver, 15);
					wait.until(ExpectedConditions.titleContains(webTitle));
				} catch (Exception e) {
					test.log(Status.ERROR, "timeout 15s not find window title=" + webTitle);
					e.printStackTrace();
				}

				String title = driver.getTitle();
				ThreadTime.sleepTime(1);
				if (title.contains(webTitle)) {
					bl = true;
				}
				test.log(Status.INFO, "current title=" + title + "  target title=" + webTitle);
			}

		}
		ThreadTime.sleepTime(1);
		test.log(Status.INFO, "close WebDriver Url=" + driver.getCurrentUrl());
		driver.close();
		ThreadTime.sleepTime(1);
		driver.switchTo().window(whandle);
		ThreadTime.sleepTime(1);
		test.log(Status.INFO, "switchTO windows Url=" + driver.getCurrentUrl());
		return bl;
	}

	/**
	 * 鼠标悬停 ele1再移至ele2点击
	 * 
	 * @param formEle
	 * @param toEle
	 * @param driver
	 */
	public boolean moveEleClickLink(WebElement formEle, WebElement toEle, String webTitle) {
		Actions action = new Actions(driver);
		action.moveToElement(formEle).perform();
		test.log(Status.INFO, "mouse movoTo:" + formEle.toString());
		try {
			WebDriverWait wait = new WebDriverWait(driver, 15);
			wait.until(ExpectedConditions.elementToBeClickable(toEle));
		} catch (Exception e) {
			test.log(Status.ERROR, "timeout 15s not find toEle=" + toEle.toString());
			e.printStackTrace();
		}
		return moveEleClickLink(toEle, webTitle);
	}

	/**
	 * 鼠标悬停 ele1再移至ele2点击ele3
	 * 
	 * @param formEle
	 * @param toEle
	 * @param driver
	 */
	public boolean moveEleClickLink(WebElement formEle, WebElement midEle, WebElement toEle, String webTitle) {
		Actions action = new Actions(driver);
		action.moveToElement(formEle).perform();
		test.log(Status.INFO, "mouse movoTo:" + formEle.toString());
		try {
			WebDriverWait wait = new WebDriverWait(driver, 15);
			wait.until(ExpectedConditions.elementToBeClickable(toEle));
		} catch (Exception e) {
			test.log(Status.ERROR, "timeout 15s not find toEle=" + toEle.toString());
			e.printStackTrace();
		}
		return moveEleClickLink(midEle, toEle, webTitle);
	}

	/**
	 * 鼠标悬停 ele1再移至ele2点击
	 * 
	 * @param formEle
	 * @param toEle
	 * @param driver
	 */
	public void actionClick(WebDriver driver, WebElement formEle, WebElement toEle) {
		Actions action = new Actions(driver);
		action.moveToElement(formEle).perform();
		ThreadTime.sleepTime(1);
		action.moveToElement(toEle).click().perform();
		ThreadTime.sleepTime(1);
	}

	public void actionClick(WebDriver driver, WebElement formEle) {
		Actions action = new Actions(driver);
		action.moveToElement(formEle).perform();
		ThreadTime.sleepTime(1);
	}

	public static By getBy(WebDriver driver, String path, String type) {
		By by = null;
		switch (type) {
		case "id":
			by = By.id(path);
			break;
		case "name":
			by = By.name(path);
			break;
		case "linkText":
			by = By.linkText(path);
			break;
		case "partialLinkText":
			by = By.partialLinkText(path);
			break;
		case "className":
			by = By.className(path);
			break;
		case "tagName":
			by = By.tagName(path);
			break;
		case "xpath":
			by = By.xpath(path);
			break;
		case "cssSelector":
			by = By.cssSelector(path);
			break;
		default:
			log.error("url=" + driver.getCurrentUrl() + ",findType=" + type + ",searchCondition=" + path + ",类型不符合要求");
		}
		return by;
	}

	public static List<WebElement> getWebElementList(WebDriver driver, String path, String type) {
		List<WebElement> ele = null;
		if (getBy(driver, path, type) != null) {
			ele = driver.findElements(getBy(driver, path, type));
		}
		if (ele.size() == 0) {
			log.error("url=" + driver.getCurrentUrl() + ",findType=" + type + ",searchCondition=" + path + ",没有找到元素");
		} else if(ele.size()==1){
			log.info("url=" + driver.getCurrentUrl() + ",findType=" + type + ",searchCondition=" + path + ",找到元素");
		}else {
			log.info("url=" + driver.getCurrentUrl() + ",findType=" + type + ",searchCondition=" + path + ",找到多个元素");
		}
		return ele;
	}
	
	public static WebElement getWebElement(WebDriver driver, String path, String type) {
		List<WebElement> ele = null;
		if (getBy(driver, path, type) != null) {
			ele = driver.findElements(getBy(driver, path, type));
		}
		if (ele.size() == 0) {
			log.error("url=" + driver.getCurrentUrl() + ",findType=" + type + ",searchCondition=" + path + ",没有找到元素");
			return null;
		} else if(ele.size()==1){
			log.info("url=" + driver.getCurrentUrl() + ",findType=" + type + ",searchCondition=" + path + ",找到元素");
		}else {
			log.error("url=" + driver.getCurrentUrl() + ",findType=" + type + ",searchCondition=" + path + ",找到多个元素");
			return null;
		}
		return ele.get(0);
	}

	/**
	 * webElement元素是否存在
	 * 
	 * @param driver
	 * @param path   查找路径
	 * @param type   路径的类型
	 * @return
	 */
	public boolean isElement(WebDriver driver, String path, String type) {
		List<WebElement> list = getWebElementList(driver, path, type);
		if (list.size() > 0) {
			return true;
		}
		return false;
	}

	/**
	 * javaScript Alert弹框处理
	 * 
	 * @param bl true表示接受，false表示取消
	 */
	public void alertClick(WebDriver driver, boolean bl) {
		Alert alert = driver.switchTo().alert();
		if (bl) {
			alert.accept();
		} else {
			alert.dismiss();
		}
	}

	/**
	 * 超时等待页面元素加载
	 * 
	 * @param by       查找条件
	 * @param waitTime 等待时间
	 * @return
	 */
	public WebElement getWaitWebElement(WebDriver driver, String path, String type, int waitTime) {
		WebElement ele = null;
		try {
			WebDriverWait wait = new WebDriverWait(driver, waitTime);
			ele = wait.until(ExpectedConditions.visibilityOfElementLocated(getBy(driver, path, type)));
			log.info("元素在页面显示;" + type + "=" + path);
		} catch (Exception e) {
			log.error("元素在页面未显示;" + type + "=" + path);
		}
		return ele;
	}
	
	/**
	 * 超时等待页面元素加载
	 * 
	 * @param by       查找条件
	 * @param waitTime 等待时间
	 * @return
	 */
	public boolean getWaitIsDisplay(WebDriver driver, String path, String type, int waitTime) {
		WebElement ele = null;
		try {
			WebDriverWait wait = new WebDriverWait(driver, waitTime);
			ele = wait.until(ExpectedConditions.visibilityOfElementLocated(getBy(driver, path, type)));
			log.info("元素在页面显示;" + type + "=" + path);
			return false;
		} catch (Exception e) {
			log.error("元素在页面未显示;" + type + "=" + path);
		}
		return true;
	}

	/**
	 * 超时等待页面元素可点击
	 * 
	 * @param by       查找条件
	 * @param waitTime 等待时间
	 * @return
	 */
	public WebElement getClickWebElement(WebDriver driver, String path, String type, int waitTime) {
		WebElement ele = null;
		try {
			WebDriverWait wait = new WebDriverWait(driver, waitTime);
			ele = wait.until(ExpectedConditions.elementToBeClickable(getBy(driver, path, type)));
			log.info("元素在页面可点击;" + type + "=" + path);
		} catch (Exception e) {
			log.error("元素在页面不可点击;" + type + "=" + path);
		}
		return ele;
	}
	
	/**
	 * 强制刷新网页 ctrl+F5
	 */
	public void refreshIE(){
//		Robot robot;
//		try {
//			robot = new java.awt.Robot();
//			//Ctrl+F5
//			robot.keyPress(KeyEvent.VK_CONTROL);
//			robot.keyPress(KeyEvent.VK_F5);
//			robot.keyRelease(KeyEvent.VK_F5);
//			robot.keyRelease(KeyEvent.VK_CONTROL);
//		}catch (Exception e) {
//			// TODO: handle exception
//		}
		Actions action=new Actions(driver);
		action.keyDown(Keys.CONTROL).sendKeys("F5").keyUp(Keys.CONTROL).perform();
	}

	public void Screenshot() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
        String dateString = format.format(new Date());
        
		String fileName="test-output/"+dateString+".jpg";
		File scrFile = ((RemoteWebDriver) driver).getScreenshotAs(OutputType.FILE);
		try {
			Files.copy(scrFile,new File(fileName));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void ScreenshotRobot(String fileName) {
		BufferedImage img=null;
		try {
			img=new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
			ImageIO.write(img, "jpg", new File(fileName));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
    public void ScreenshotByElement(WebElement element) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
        String dateString = format.format(new Date());
		String fileName="test-output/"+dateString+".jpg";
		
        //创建全屏截图
        WrapsDriver wrapsDriver = (WrapsDriver)element;
        File screen = ((RemoteWebDriver)wrapsDriver.getWrappedDriver()).getScreenshotAs(OutputType.FILE);
        BufferedImage image = ImageIO.read(screen);
        //获取元素的高度、宽度
        int width = element.getSize().getWidth();
        int height = element.getSize().getHeight();
         
        //创建一个矩形使用上面的高度，和宽度
        Rectangle rect = new Rectangle(width, height);
        //元素坐标
        Point p = element.getLocation();
        BufferedImage img = image.getSubimage(p.getX(), p.getY(), rect.width, rect.height);
        ImageIO.write(img, "jpg",  new File(fileName));
    }
	
    
}
